package inputstream;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * FileInputStream成员方法:
 *  public int read(byte[] b) throws IOException
 *      1.从关联文件中尽可能多的读取字节到字节数组中(最多不超过字节数组的长度),我们可以从字节数组中取数据
 *      2.返回值代表 每次装入字节数组中的总字节个数(读到的字节个数)
 * String类:
 *  构造方法:
 *      public String(byte[] bytes):将字节数组按照平台默认码表(UTF-8)转换为字符串
 *      public String(byte[] bytes, int offset, int length):
 *          将字节数组中,从offset位置开始,指定length个长度的字节(包含offset位置字节)转换成字符串
 */
public class FileInputStreamDemo02 {
    public static void main(String[] args)throws Exception {
        //method01();
        FileInputStream fis = new FileInputStream("day22-Io-01/6.txt");
        byte[] bytes = new byte[2];

/*        int length01 = fis.read(bytes);
        System.out.println(length01 + " " + new String(bytes));//2 ab

        int length02 = fis.read(bytes);
        System.out.println(length02 + " " + new String(bytes));//2 cd

        int length03 = fis.read(bytes);
        System.out.println(length03 + " " + new String(bytes));//1 ed
                                                                // ed的原因 字节数组每次都会更新读取到的字节并且覆盖掉原来的值,但是当读到末尾的时候,
                                                                //只有一个e字节覆盖了原来的字节,d并没有被覆盖因此会打印ed

        int length04 = fis.read(bytes);
        System.out.println(length04 + " " + new String(bytes));//-1 ed*/

        int length;
        while ((length = fis.read(bytes)) != -1) {
            System.out.println(new String(bytes, 0, length));
        }
        fis.close();
    }

    private static void method01() throws IOException {
        FileInputStream fis = new FileInputStream("day22-Io-01/6.txt");
        byte[] bytes = new byte[2];

        fis.read(bytes);//一次性从6.txt中读取了两个字节 97,98存到了byte数组中

        for (byte b : bytes) {
            System.out.println((char) b);
        }

        fis.close();
    }
}
